/**
 * 屏幕级可复用组件库
 * 提供页面级别的复合组件，提高开发效率和代码复用性
 * 
 * 主要组件：
 * - UserProgressCard: 用户进度卡片组件
 * - LessonCard: 课程卡片组件  
 * - StatisticsGrid: 统计数据网格组件
 * - AchievementsList: 成就列表组件
 * - SettingsMenu: 设置菜单组件
 * 
 * 作者：AI语言学习应用开发团队
 * 创建时间：2024年
 * 更新时间：2024年
 */
import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Dimensions, Alert, Share, Platform } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import * as Progress from 'react-native-progress';
import { AppCard, StatusIndicator, Tag } from './CommonUI';
import { NumberUtils, DateUtils } from '../utils/CommonUtils';

const { width } = Dimensions.get('window');

/**
 * 用户进度卡片组件
 * 显示用户学习进度、等级信息和激励文字
 * @param {Object} props - 组件属性
 * @param {Object} props.userProgress - 用户进度数据
 * @param {number} props.userProgress.level - 用户等级
 * @param {number} props.userProgress.totalXP - 总经验值
 * @param {number} props.userProgress.currentStreak - 当前连续天数
 * @param {number} props.userProgress.lessonsCompleted - 已完成课程数
 * @param {number} props.userProgress.totalLessons - 总课程数
 * @param {string} props.username - 用户名，默认为"学习者"
 * @param {Object} props.style - 自定义样式
 */
export function UserProgressCard({ 
  userProgress = {}, 
  username = '学习者',
  style 
}) {
  // 安全地获取用户进度数据
  const {
    level = 1,
    totalXP = 0,
    currentStreak = 0,
    lessonsCompleted = 0,
    totalLessons = 6
  } = userProgress;

  // 计算完成百分比
  const completionPercentage = totalLessons > 0 ? (lessonsCompleted / totalLessons) * 100 : 0;
  
  // 生成激励文字
  const getMotivationText = () => {
    if (lessonsCompleted === 0) {
      return "🚀 开始你的学习之旅吧！";
    } else if (lessonsCompleted === totalLessons) {
      return "🎉 恭喜完成所有课程！";
    } else {
      return `💪 还有 ${totalLessons - lessonsCompleted} 个课程等你挑战`;
    }
  };
  
  /**
   * 分享学习进度功能
   * 使用系统原生分享功能
   */
  const handleShareProgress = async () => {
    try {
      // 生成分享数据
      const shareData = {
        title: `${username}的学习成果`,
        message: `我在AI英语学习应用中已经完成了${lessonsCompleted}个课程，获得了${totalXP}XP！连续学习${currentStreak}天！一起来学习吧！`
      };
      
      // 使用原生Share API
      if (Platform.OS === 'ios' || Platform.OS === 'android') {
        await Share.share({
          title: shareData.title,
          message: shareData.message
        });
      } else {
        // Web版本的处理
        if (navigator.share) {
          await navigator.share(shareData);
        } else {
          // 复制到剪贴板
          await navigator.clipboard.writeText(shareData.message);
          Alert.alert('分享成功', '分享内容已复制到剪贴板');
        }
      }
      
    } catch (error) {
      console.error('分享失败:', error);
      Alert.alert('分享失败', '无法分享您的学习进度，请稍后重试。');
    }
  };

  return (
    <AppCard style={[styles.userProgressCard, style]}>
      {/* 用户基本信息区域 */}
      <View style={styles.userInfo}>
        <View style={styles.avatarContainer}>
          <Ionicons name="person" size={24} color="#58CC02" />
        </View>
        <View style={styles.userDetails}>
          <Text style={styles.userName}>{username}</Text>
          <Text style={styles.levelText}>
            等级 {level} · {NumberUtils.formatXP(totalXP)}
          </Text>
        </View>
        {/* 连续学习天数快览 */}
        <View style={styles.quickStats}>
          <View style={styles.quickStatItem}>
            <Text style={styles.quickStatNumber}>{currentStreak}</Text>
            <Text style={styles.quickStatLabel}>天</Text>
          </View>
        </View>
        {/* 分享按钮 */}
        <TouchableOpacity 
          style={styles.shareButton} 
          onPress={handleShareProgress}
          activeOpacity={0.7}
        >
          <Ionicons name="share-outline" size={20} color="#58CC02" />
        </TouchableOpacity>
      </View>
      
      {/* 学习进度区域 */}
      <View style={styles.progressContainer}>
        <View style={styles.progressHeader}>
          <View style={styles.progressInfo}>
            <Ionicons name="trophy-outline" size={16} color="#58CC02" />
            <Text style={styles.progressLabel}>学习进度</Text>
          </View>
          <Text style={styles.progressText}>
            {lessonsCompleted}/{totalLessons} 课程
          </Text>
        </View>
        
        {/* 进度条容器 */}
        <View style={styles.progressBarContainer}>
          <Progress.Bar
            progress={lessonsCompleted / totalLessons}
            width={width - 80}
            height={8}
            color="#58CC02"
            unfilledColor="#E8F5E8"
            borderWidth={0}
            borderRadius={4}
          />
          <Text style={styles.progressPercentage}>
            {Math.round(completionPercentage)}%
          </Text>
        </View>
        
        {/* 激励文字 */}
        <Text style={styles.motivationText}>
          {getMotivationText()}
        </Text>
      </View>
    </AppCard>
  );
}

/**
 * 课程卡片组件
 * 显示单个课程的信息、状态和进度
 * @param {Object} props - 组件属性
 * @param {Object} props.lesson - 课程数据对象
 * @param {number} props.index - 课程索引
 * @param {string} props.status - 课程状态：'completed', 'available', 'locked'
 * @param {Object} props.progressData - 课程进度数据
 * @param {Function} props.onPress - 点击回调函数
 * @param {Object} props.style - 自定义样式
 */
export function LessonCard({ 
  lesson, 
  index = 0, 
  status = 'available', 
  progressData = null,
  onPress,
  style 
}) {
  if (!lesson) return null;

  return (
    <AppCard
      style={[
        styles.lessonCard,
        status === 'completed' && styles.completedCard,
        status === 'locked' && styles.lockedCard,
        style
      ]}
      onPress={onPress}
      disabled={status === 'locked'}
    >
      <View style={styles.lessonHeader}>
        {/* 课程状态指示器 */}
        <StatusIndicator 
          status={status === 'completed' ? 'completed' : status === 'locked' ? 'locked' : 'available'}
          style={styles.lessonStatusIndicator}
        />
        
        {/* 课程信息 */}
        <View style={styles.lessonInfo}>
          <Text style={[
            styles.lessonTitle,
            status === 'locked' && styles.lockedText
          ]}>
            {lesson.title}
          </Text>
          <Text style={[
            styles.lessonDescription,
            status === 'locked' && styles.lockedText
          ]}>
            {lesson.description}
          </Text>
          {/* 显示尝试次数和最高得分 */}
          {progressData && progressData.attempts > 0 && (
            <Text style={styles.attemptInfo}>
              🎯 尝试次数: {progressData.attempts}
              {progressData.bestScore && ` | 最高得分: ${progressData.bestScore}分`}
            </Text>
          )}
        </View>
        
        {/* 课程元数据 */}
        <View style={styles.lessonMeta}>
          <Tag
            text={`${lesson.xp} XP`}
            variant="success"
            icon="star"
            style={styles.xpTag}
          />
          <Text style={[
            styles.difficultyText,
            status === 'locked' && styles.lockedText
          ]}>
            {lesson.difficulty}
          </Text>
        </View>
      </View>
    </AppCard>
  );
}

/**
 * 统计数据网格组件
 * 以网格形式展示用户的各项学习统计
 * @param {Object} props - 组件属性
 * @param {Array} props.statistics - 统计数据数组
 * @param {Object} props.style - 自定义样式
 */
export function StatisticsGrid({ statistics = [], style }) {
  /**
   * 渲染单个统计卡片
   * @param {Object} stat - 统计数据对象
   * @param {string} stat.icon - 图标名称
   * @param {string} stat.title - 标题
   * @param {string} stat.value - 数值
   * @param {string} stat.subtitle - 副标题
   * @param {string} stat.color - 颜色
   * @param {number} index - 索引
   */
  const renderStatCard = (stat, index) => (
    <AppCard key={index} style={styles.statCard}>
      <View style={[styles.statIcon, { backgroundColor: stat.color || '#58CC02' }]}>
        <Ionicons name={stat.icon} size={24} color="#fff" />
      </View>
      <View style={styles.statContent}>
        <Text style={styles.statValue}>{stat.value}</Text>
        <Text style={styles.statTitle}>{stat.title}</Text>
        {stat.subtitle && <Text style={styles.statSubtitle}>{stat.subtitle}</Text>}
      </View>
    </AppCard>
  );

  return (
    <View style={[styles.statsGrid, style]}>
      {statistics.map(renderStatCard)}
    </View>
  );
}

/**
 * 成就列表组件
 * 显示用户的成就列表，包括已解锁和未解锁的成就
 * @param {Object} props - 组件属性
 * @param {Array} props.achievements - 成就数据数组
 * @param {Function} props.onAchievementPress - 成就点击回调
 * @param {Object} props.style - 自定义样式
 */
export function AchievementsList({ achievements = [], onAchievementPress, style }) {
  /**
   * 渲染单个成就项
   * @param {Object} achievement - 成就数据对象
   * @param {number} index - 索引
   */
  const renderAchievement = (achievement, index) => (
    <AppCard
      key={achievement.id || index}
      style={[
        styles.achievementCard,
        achievement.unlocked && styles.unlockedAchievement
      ]}
      onPress={() => onAchievementPress && onAchievementPress(achievement)}
    >
      <StatusIndicator 
        status={achievement.unlocked ? 'completed' : 'locked'}
        style={styles.achievementStatusIndicator}
      />
      
      <View style={styles.achievementContent}>
        <Text style={[
          styles.achievementTitle,
          achievement.unlocked && styles.unlockedTitle
        ]}>
          {achievement.title}
        </Text>
        <Text style={[
          styles.achievementDescription,
          achievement.unlocked && styles.unlockedDescription
        ]}>
          {achievement.description}
        </Text>
        {achievement.unlocked && achievement.unlockedAt && (
          <Text style={styles.unlockedDate}>
            解锁时间：{DateUtils.formatDate(achievement.unlockedAt, 'date')}
          </Text>
        )}
      </View>
      
      {achievement.unlocked && (
        <View style={styles.checkmarkContainer}>
          <Ionicons name="checkmark-circle" size={24} color="#4CAF50" />
        </View>
      )}
    </AppCard>
  );

  return (
    <View style={[styles.achievementsList, style]}>
      {achievements.map(renderAchievement)}
    </View>
  );
}

/**
 * 设置菜单组件
 * 提供应用设置选项的菜单界面
 * @param {Object} props - 组件属性
 * @param {Array} props.menuItems - 菜单项数组
 * @param {Function} props.onItemPress - 菜单项点击回调
 * @param {Object} props.style - 自定义样式
 */
export function SettingsMenu({ menuItems = [], onItemPress, style }) {
  /**
   * 渲染单个设置项
   * @param {Object} item - 设置项数据
   * @param {string} item.id - 设置项ID
   * @param {string} item.icon - 图标名称
   * @param {string} item.title - 标题
   * @param {string} item.subtitle - 副标题
   * @param {string} item.textColor - 文字颜色
   * @param {boolean} item.showChevron - 是否显示右箭头
   * @param {number} index - 索引
   */
  const renderSettingItem = (item, index) => (
    <TouchableOpacity
      key={item.id || index}
      style={styles.settingItem}
      onPress={() => onItemPress && onItemPress(item)}
      activeOpacity={0.7}
    >
      <Ionicons 
        name={item.icon} 
        size={24} 
        color={item.textColor || "#666"} 
      />
      <View style={styles.settingTextContainer}>
        <Text style={[
          styles.settingText, 
          item.textColor && { color: item.textColor }
        ]}>
          {item.title}
        </Text>
        {item.subtitle && (
          <Text style={styles.settingSubtitle}>{item.subtitle}</Text>
        )}
      </View>
      {item.showChevron !== false && (
        <Ionicons name="chevron-forward" size={20} color="#ccc" />
      )}
    </TouchableOpacity>
  );

  return (
    <View style={[styles.settingsMenu, style]}>
      {menuItems.map(renderSettingItem)}
    </View>
  );
}

/**
 * 底部提示组件
 * 显示学习提示和鼓励信息
 * @param {Object} props - 组件属性
 * @param {string} props.text - 提示文本
 * @param {string} props.icon - 图标名称
 * @param {Object} props.style - 自定义样式
 */
export function BottomTip({ 
  text = "💡 每天坚持学习15分钟，连续打卡可获得更多奖励！",
  icon = "bulb-outline",
  style 
}) {
  return (
    <View style={[styles.bottomTip, style]}>
      <Ionicons name={icon} size={20} color="#58CC02" />
      <Text style={styles.tipText}>{text}</Text>
    </View>
  );
}

// 样式定义
const styles = StyleSheet.create({
  // 用户进度卡片样式
  userProgressCard: {
    backgroundColor: '#fff',
    marginHorizontal: 0,
    marginTop: 20,
    marginBottom: 16,
    borderRadius: 16,
    padding: 18,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
  },
  
  userInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  
  avatarContainer: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: '#E8F5E8',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  
  userDetails: {
    flex: 1,
  },
  
  userName: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
    marginBottom: 2,
  },
  
  levelText: {
    fontSize: 14,
    color: '#666',
  },
  
  quickStats: {
    alignItems: 'center',
  },
  
  quickStatItem: {
    alignItems: 'center',
  },
  
  quickStatNumber: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#58CC02',
  },
  
  quickStatLabel: {
    fontSize: 12,
    color: '#666',
    marginTop: 2,
  },
  
  progressContainer: {
    marginTop: 12,
  },
  
  progressHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
  },
  
  progressInfo: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  
  progressLabel: {
    fontSize: 14,
    fontWeight: '600',
    color: '#333',
    marginLeft: 6,
  },
  
  progressText: {
    fontSize: 14,
    fontWeight: '600',
    color: '#58CC02',
  },
  
  progressBarContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  
  progressPercentage: {
    fontSize: 12,
    fontWeight: '600',
    color: '#58CC02',
    marginLeft: 10,
    minWidth: 35,
  },
  
  motivationText: {
    fontSize: 14,
    color: '#666',
    textAlign: 'center',
    fontStyle: 'italic',
  },
  
  // 课程卡片样式
  lessonCard: {
    backgroundColor: '#fff',
    marginHorizontal: 20,
    marginVertical: 8,
    borderRadius: 16,
    padding: 16,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
  },
  
  completedCard: {
    backgroundColor: '#f8fff8',
    borderLeftWidth: 4,
    borderLeftColor: '#4CAF50',
  },
  
  lockedCard: {
    backgroundColor: '#f5f5f5',
    opacity: 0.7,
  },
  
  lessonHeader: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  
  lessonStatusIndicator: {
    marginRight: 12,
  },
  
  lessonInfo: {
    flex: 1,
    marginRight: 12,
  },
  
  lessonTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
    marginBottom: 4,
  },
  
  lessonDescription: {
    fontSize: 14,
    color: '#666',
    marginBottom: 4,
  },
  
  lockedText: {
    color: '#999',
  },
  
  attemptInfo: {
    fontSize: 12,
    color: '#58CC02',
    marginTop: 4,
  },
  
  lessonMeta: {
    alignItems: 'flex-end',
  },
  
  xpTag: {
    marginBottom: 8,
  },
  
  difficultyText: {
    fontSize: 12,
    color: '#666',
    fontWeight: '500',
  },
  
  // 统计网格样式
  statsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
  },
  
  statCard: {
    width: (width - 60) / 2,
    marginBottom: 16,
    padding: 16,
    flexDirection: 'row',
    alignItems: 'center',
  },
  
  statIcon: {
    width: 48,
    height: 48,
    borderRadius: 24,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  
  statContent: {
    flex: 1,
  },
  
  statValue: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 2,
  },
  
  statTitle: {
    fontSize: 12,
    color: '#666',
    marginBottom: 2,
  },
  
  statSubtitle: {
    fontSize: 10,
    color: '#999',
  },
  
  // 成就列表样式
  achievementsList: {
    paddingHorizontal: 20,
  },
  
  achievementCard: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    marginBottom: 12,
    backgroundColor: '#f8f8f8',
    borderRadius: 12,
  },
  
  unlockedAchievement: {
    backgroundColor: '#fff',
    borderLeftWidth: 4,
    borderLeftColor: '#4CAF50',
  },
  
  achievementStatusIndicator: {
    marginRight: 12,
  },
  
  achievementContent: {
    flex: 1,
    marginRight: 12,
  },
  
  achievementTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#999',
    marginBottom: 4,
  },
  
  unlockedTitle: {
    color: '#333',
  },
  
  achievementDescription: {
    fontSize: 14,
    color: '#ccc',
    marginBottom: 4,
  },
  
  unlockedDescription: {
    color: '#666',
  },
  
  unlockedDate: {
    fontSize: 12,
    color: '#4CAF50',
    fontStyle: 'italic',
  },
  
  checkmarkContainer: {
    padding: 4,
  },
  
  // 设置菜单样式
  settingsMenu: {
    backgroundColor: '#fff',
    borderRadius: 12,
    marginHorizontal: 20,
    marginVertical: 8,
    overflow: 'hidden',
  },
  
  settingItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 16,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  
  settingTextContainer: {
    flex: 1,
    marginLeft: 16,
  },
  
  settingText: {
    fontSize: 16,
    color: '#333',
    fontWeight: '500',
  },
  
  settingSubtitle: {
    fontSize: 14,
    color: '#666',
    marginTop: 2,
  },
  
  // 底部提示样式
  bottomTip: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#E8F5E8',
    marginHorizontal: 20,
    marginVertical: 16,
    padding: 16,
    borderRadius: 12,
    borderLeftWidth: 4,
    borderLeftColor: '#58CC02',
  },
  
  tipText: {
    flex: 1,
    fontSize: 14,
    color: '#333',
    marginLeft: 12,
    lineHeight: 20,
  },
  
  // 分享按钮样式
  shareButton: {
    padding: 8,
    borderRadius: 20,
    backgroundColor: '#E8F5E8',
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: 8,
  },
});